// 定义页面的modal大小
function setModalSize() {
	var documentW = $(window).width();
	var documentH = $(window).height();
	$('#modalW').width(documentW * 0.7);
	$('#chart').width(documentW *0.680)
	$('#modalH,#chart').height(documentH * 0.8);
}


jQuery(document).ready(function() {
	$.ajax({
		async : false,
		url : projectPath + "user/getCurrentUser.do",
		data : {},
		dataType : "json",
		success : function(data) {
			$('#org').val(data.orgname);
			$('#org').attr('data', data.orgcode);
		}
	});

	initTable();
	App.setPage("tjconsultation");  //Set current page
	App.init();  
 
	//列表查询事件
	$('#search').click(function(){
		$('#table').bootstrapTable(('refresh'));  // 很重要的一步，刷新url！
	});
	
 
	//绑定机构下拉列表
	bindOrg2('org');
	var dataList = null;
	var date = new Date();      
	var time = date.Format("yyyy-MM-dd");
	$('input[type="date"]').each(function(){//限制时间只能选择当前时间或者以前
		 $(this).popover('hide');
		 $(this).attr("max",time);
	})
	
	
	$("[data-toggle='popover']").popover( {
		content:function(){
			return $('.popover-content').html(); 
		}
	});
});	


function hidePop(){//隐藏弹出框
	$("[data-toggle='popover']").popover('hide');
}
function exp(type, fn, dl) {//table导出
	$("[data-toggle='popover']").popover('hide');
	var elt = document.getElementById('table');
	var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
	return dl ?
		XLSX.write(wb, {bookType:type, bookSST:true, type: 'base64'}) :
		XLSX.writeFile(wb, fn || (getExcelFileName('咨询统计')+'.' + (type || 'xlsx')));
}

function getExcelFileName(name) {  
    var d = new Date();  
    var curYear = d.getYear();  
    var curMonth = "" + (d.getMonth() + 1);  
    var curDate = "" + d.getDate();  
    var curHour = "" + d.getHours();  
    var curMinute = "" + d.getMinutes();  
    var curSecond = "" + d.getSeconds();  
    if (curMonth.length == 1) {  
        curMonth = "0" + curMonth;  
    }  

    if (curDate.length == 1) {  
        curDate = "0" + curDate;  
    }  

    if (curHour.length == 1) {  
        curHour = "0" + curHour;  
    }  

    if (curMinute.length == 1) {  
        curMinute = "0" + curMinute;  
    }  

    if (curSecond.length == 1) {  
        curSecond = "0" + curSecond;  
    }  
    var fileName = name + "_" + curYear + curMonth + curDate + "_"  
            + curHour + curMinute + curSecond;  
    return fileName;  

}  


function initTable(){	
	$('#table').bootstrapTable({
		url:basePath() + 'statistics/consultationStatistics.do',
        striped: true,      //是否显示行间隔色
        dataType: "json",
        contentType: "application/json",
		method: 'post',
        sidePagination: "server",
    	queryParams:function(params){
        	var param  = {
                	endTime:$('#date').find('input[type="date"]:eq(1)').val(),
                	startTime: $('#date').find('input[type="date"]:eq(0)').val(),
                	orgCode:$("#org").attr("data")
                };
        		return param;
        },
	    columns: [
	    	{field:'ORGNAME',title:'机构名称',align:'center',  width:'40%'},
	    	{field:'TYPE',title:'类型',align:'center',  width:'30%'} ,
	    	{field:'TOTAL',title:'总数',align:'center',  width:'30%'}],
	   onLoadSuccess:function(dataList){
		   if(dataList!=null){
				if(dataList.rows.length>0){
					$('.disabled').each(function(index,e){
						$(this).removeClass('disabled');
					})
				}else{
					$('#btn a').each(function(index,e){
						$(this).addClass('disabled');
					})
				}
			}
		   
		   
		   $('#lineChart,#barChart').click(function(){//统计图 模态窗
				setModalSize();
				if($(this).attr("id")=="lineChart"){
					$('#modalTile').html("折线图");
					if(dataList!=null)
						initChart('line',dataList);
				}else{
					$('#modalTile').html("柱状图");
					if(dataList!=null)
						initChart('bar',dataList);
				}
				$("#modal").modal('show');
			});
	   }
	});
}

function initChart(type,data){
	var myChart = echarts.init(document.getElementById('chart')); 
	   data = data.rows;
	  var series  = [];
	  var legends =[];
	  var xAxis =[];
	  for(var i =0;i<data.length;i++){
		  
		  for(var key in data[i]){
			 if(key!="ORGNAME"&&key!="TYPE"){
				if($.inArray(key, legends)<0 ){
					legends.push(key);
				}
			 }
		  }
		xAxis.push(data[i].ORGNAME );
	  }
	  for(var i = 0;i<legends.length;i++){//计算series
		  var serie = {
				  name:legends[i],
				  type:type,
				  data:[]
		  }
		  for(var j=0;j<data.length;j++){
			  serie.data.push(data[j][legends[i]]);
		  }
		  series.push(serie);
	  }
	  myChart.setOption({
		toolbox:{
			show:true,
			feature:{
				saveAsImage:{
					show:true,
					name:'咨询统计',
					excludeComponents:['toolbox']
				}
			}
		},
      	tooltip: {
              show: true
          },
          legend: {
              data:legends
          },
          grid:{
        	  y2:200
          },
          xAxis : [
              {
                  type : 'category',
                  boundaryGap:[0,0.01],
                  data : xAxis,
                  axisLabel:{
                	  rotate:40,
                	  interval:0
                  }
              }
          ],
          yAxis : [
              {
                  type : 'value'
              }
          ],
          series : series
      }); 
}



/**时间格式化**/
Date.prototype.Format = function (fmt) {  
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
} 


 